<?php
/**
 * 信誉用户
 * @author Ice <iceinto@mallog.com.cn>
 */
class CreditUserModel extends BaseModel
{
	/**
	 * 获取用户分值
	 * @param int $uid 用户
	 * @param int $tid 类型
	 * @author Ice <iceinto@mallog.com.cn>
	 */
	public function getUserNum($uid, $tid){
		$map = array();
		$map['uid'] = $uid;
		$map['tid'] = $tid;
		return $this->where($map)->find();
	}
	/**
	 * 修改用户信誉信息
	 * @param int $uid 用户
	 * @param int $rid 规则
	 * @param int $num 分值
	 * @author Ice <iceinto@mallog.com.cn>
	 */
	public function change($uid, $rid, $num = 0){
		$rs = false;
		$data = array();
		//获取规则记录
		$rule = M('CreditRule')->find($rid);
		$rs = $this->checkRule(&$rule, $uid); //验证规则是否满足条件
		$rule['num'] = $rule['num'] ? $rule['num'] : $num;
		//添加日志记录
		if($rule && $rs){
			$data['uid'] = $uid;
			$data['rid'] = $rule['id'];
			$data['tid'] = $rule['tid'];
			$data['create_time'] = time();
			$data['num'] = $rule['num'];
			$data['operator'] = $rule['operator'];
			$rs = M('CreditLog')->add($data); //执行日志添加
			if($rule && !$rs){
				return $rs; //返回错误结果不在继续处理
			}
		}
		if($rule && $rs){
			//修改用户对应类型积分信息
			$rs = $this->edit($uid, $rule['tid'], $rule['num'], $rule['operator']);
		}
		return $rs;
	}

	/**
	 * 修改和添加用户信用积分
	 * @param int $uid 用户
	 * @param int $tid 类型
	 * @param int $num 分值
	 * @param int $eperator 操作符
	 * @author Ice <iceinto@mallog.com.cn>
	 */
	public function edit($uid, $tid, $num, $eperator = 1){
		$rs = false;
		$map = array();
		$data = array();
		//查看用户信息是否存在
		$map['uid'] = $uid;
		$map['tid'] = $tid;
		$data['update_time'] = time(); //更新时间
		$user = $this->where($map)->find();
		if($user){
			//如果存在修改
			if($eperator == 1){
				$data['num'] =  array('exp','num+'.$num); //积分添加
			}else if($eperator == 2){
				$data['num'] =  array('exp','num-'.$num); //积分减少
			}else{
				return $rs;
			}
			$rs = $this->where($map)->save($data);
		}else{
			//如果不存在添加
			$data['uid'] = $uid;
			$data['tid'] = $tid;
			$data['num'] = $num;
			$rs = $this->add($data);
		}
		return $rs;
	}


	/**
	 * 判断添加是否满足规则
	 * @param array $rule 规则
	 * @author Ice <iceinto@mallog.com.cn>
	 */
	public function checkRule(&$rule, $uid){
		$rs = false;
		$map = array();
		$CreditLogModel = D('CreditLog');
		//判断是否是循环任务
		if($rule['repeat'] && $rule['frequency']){
			//查看rule log 记录判断时间
			//获取当天记录中此类操作信息
			$count = $CreditLogModel->findDayCount($uid, $rule['tid'], $rule['id']);
			if($count < $rule['frequency']){
				//执行积分处理操作
				$rs = true;
			}
		}else if(!$rule['repeat'] && $rule['frequency']){
			//获取当前类型下面所有数量
			$count = $CreditLogModel->findAllCount($uid, $rule['tid'], $rule['id']);
			if($count < $rule['frequency']){
				//执行积分处理操作
				$rs = true;
			}
		}
		else if(!$rule['repeat'] && !$rule['frequency']){
			$rs = true;
		}
		return $rs;
	}
}
?>